package com.zenithmind.chat;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 聊天服务启动类 - 遵循单一职责原则
 * 只负责应用程序的启动和基础配置
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@SpringBootApplication
@EnableTransactionManagement
@EnableCaching
@EnableAsync
@MapperScan("com.zenithmind.chat.mapper")
public class ChatServiceApplication {

    public static void main(String[] args) {
        try {
            ConfigurableApplicationContext context = SpringApplication.run(ChatServiceApplication.class, args);
            Environment env = context.getEnvironment();

            String protocol = "http";
            if (env.getProperty("server.ssl.key-store") != null) {
                protocol = "https";
            }

            String serverPort = env.getProperty("server.port", "8080");
            String contextPath = env.getProperty("server.servlet.context-path", "/");
            String hostAddress = "localhost";

            try {
                hostAddress = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.warn("无法获取主机地址，使用默认值: localhost");
            }

            log.info("\n----------------------------------------------------------\n" +
                    "聊天服务启动成功！访问地址:\n" +
                    "本地访问: \t{}://localhost:{}{}\n" +
                    "外部访问: \t{}://{}:{}{}\n" +
                    "配置文件: \t{}\n" +
                    "API文档: \t{}://localhost:{}{}/swagger-ui.html\n" +
                    "----------------------------------------------------------",
                    protocol, serverPort, contextPath,
                    protocol, hostAddress, serverPort, contextPath,
                    env.getActiveProfiles().length == 0 ? "default" : String.join(",", env.getActiveProfiles()),
                    protocol, serverPort, contextPath);

        } catch (Exception e) {
            log.error("聊天服务启动失败", e);
            System.exit(1);
        }
    }
}
